package com.buaa.hyf.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.buaa.hyf.Utils.Globals;
import com.buaa.hyf.myapplication.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

public class WelcomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        Thread thread = new Thread(){
            @Override
            public void run() {

                try {
                    InputStream in =getAssets().open("question.txt");
                    Globals.values=loadInputStream(in);
                    sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Intent intent = new Intent(WelcomeActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
            }
        };
        thread.start();
    }

    //读取文件
    public List<Map<String,Object>> loadInputStream(InputStream in) throws IOException {
        List<Map<String ,Object>> values = new ArrayList<>();
        BufferedReader br =new BufferedReader(new InputStreamReader(in,"GBK")); //字节流转换为字符流
        //读取字符流
        String line = null;
        StringBuffer question = new StringBuffer();
        StringBuffer answer = new StringBuffer();
        boolean questionFlag = false;

        while((line=br.readLine())!=null){
            if (line.equals("Start_Question_Flag")){
                //开始读问题
                questionFlag=true;
            }else if (line.equals("Start_Answer_Flag")){
                //开始读答案
                questionFlag=false;
            }else if (line.equals("End_Flag")){
                //读取结束，需要整合
                Map<String,Object> map = new Hashtable<>();
                map.put("question",question.toString());
                map.put("answer",answer.toString());
                values.add(map);
                //清空问题和答案的变量
                question = new StringBuffer();
                answer = new StringBuffer();
            }else{
                //读取数据
                if(questionFlag){
                    question.append(line);
                }else{
                    answer.append(line);
                }



            }
        }
        return values;
    }
}
